<template>
    <f7-page class="common-page has-bottom-btns">
        <f7-navbar>
            <f7-nav-left>
                <f7-link back icon-material="chevron_left" force></f7-link>
            </f7-nav-left>
            <f7-nav-title>巡检记录</f7-nav-title>
            <f7-nav-right></f7-nav-right>
        </f7-navbar>
        <v-accordion title="巡检信息" class="infoList noBorder">
            <van-form input-align="right" ref="form" :readonly="!canEdit">
                <van-field readonly :required="canEdit" clickable name="datetimePicker" :value="models.model.patrolTime"
                    label="检查时间" :rules="[{ required: true, message: '请选择检查时间' }]" placeholder="请选择"
                    :right-icon="canEdit ? 'arrow' : ''" @click="canEdit ? showTimePicker('patrolTime') : ''" />
                <van-field v-model="models.model.patrolContent" :required="canEdit" label="现场情况"
                    :rules="[{ required: true, message: '请输入现场情况' }]" rows="3" autosize
                    :type="canEdit ? 'textarea' : ''" placeholder="请输入">
                </van-field>
                <van-field name="radio" :required="canEdit" label="存在问题" :rules="[{ validator, message: '请选择存在问题' }]">
                    <van-radio-group slot="input" v-if="canEdit" :disabled="!canEdit" v-model="models.model.isQuestion"
                        direction="horizontal">
                        <van-radio v-for="(item, index) in radioArr" :key="index" :name="item.code">{{ item.name
                            }}</van-radio>
                    </van-radio-group>
                    <span slot="input" v-else>{{
                models.model.isQuestion ? "是" : "否"
            }}</span>
                </van-field>
                <van-field v-if="models.model.isQuestion" v-model="models.model.question"
                    :required="canEdit && models.model.isQuestion" label="问题描述"
                    :rules="[{ required: true, message: '请输入问题描述况' }]" rows="3" autosize
                    :type="canEdit ? 'textarea' : ''" placeholder="请输入">
                </van-field>
                <van-field :required="canEdit" label="现场照片" readonly class="field-pic">
                </van-field>
                <qm-file-upload v-if="models.model.patrolId" ref="patrolPic" :disabled="!canEdit" :params="{
                type: 'attach',
                dataKey: models.model.patrolId,
                bizType: 'mobilePatrolPhoto',
            }" uploadId="patrolPic">
                </qm-file-upload>
                <van-field v-if="models.model.isQuestion" readonly :required="canEdit && models.model.isQuestion" clickable name="datetimePicker" :value="models.model.leastReplyDate
                    ? models.model.leastReplyDate
                    : models.model.limitTime
                " :right-icon="canEdit ? 'arrow' : ''" label="限期整改时间" :rules="[{ required: true, message: '请选择限期整改时间' }]"
                    placeholder="请选择" @click="canEdit ? showTimePicker('limitTime') : ''" />
            </van-form>
        </v-accordion>
        <v-accordion title="操作记录" class="infoList noBorder" v-if="history.length">
            <v-workflow-list :data="history" showPic></v-workflow-list>
        </v-accordion>
        <f7-toolbar position="bottom" no-shadow class="fff" v-if="canEdit && !showPicker">
            <f7-button fill class="submit-btn plain-btn" @click="onSave">保存</f7-button>
            <f7-button fill class="submit-btn" @click="onCommit">提交</f7-button>
        </f7-toolbar>
        <f7-toolbar position="bottom" no-shadow class="fff" v-if="canWrite">
            <f7-button fill class="submit-btn" @click="onRectification">填写整改结果</f7-button>
        </f7-toolbar>
        <f7-toolbar position="bottom" no-shadow class="fff" v-if="canCheck">
            <f7-button fill class="submit-btn plain-btn" @click="fnCheck('reject')">退回
            </f7-button>
            <f7-button fill class="submit-btn" @click="fnCheck('pass')">通过
            </f7-button>
        </f7-toolbar>
        <!-- 审核意见 -->
        <v-popup-opinion v-model="showPinion" :selectUser="selectUser" ref="opinion" :showDate="auditType == 'reject'"
            @save="saveDetects">
        </v-popup-opinion>
        <!-- 选择日期 -->
        <van-popup v-model="showPicker" position="bottom">
            <van-datetime-picker type="date" @confirm="onConfirm" @cancel="showPicker = false" :min-date="minDate"
                :max-date="maxDate" :value="currentDate" />
        </van-popup>
    </f7-page>
</template>

<script>
import controller from "@/libs/framework/workflowController";

export default class instance extends controller {
    disableCache() {
        return true;
    }
    onBeforeInit() {
        this.urls = {
            model: "/equipment/eqmMobilePatrol/workflow/getWorkflowViewModel",
            processSave: "/equipment/eqmMobilePatrol/workflow/processSave",
        };
    }
    onInit() {
        this.context.engineeId = this.$f7route.query.engineeId;
        this.context.registerId = this.$f7route.query.registerId;
        this.$params.appCode = "mobileMachineryInspection";
    }
    onAfterQuery(type, isSuccess, result) {
        if (type == "form") {
            this.context.pageAction = result.pageAction;
            if (result.pageAction == "edit") {
                this.vm.reloadTaskId();
            }
            if (result.pageAction == "create") {
                result.models.model.patrolTime = this.vm.$formatter.formatDate(
                    new Date(),
                    "yyyy-MM-dd"
                );
            }
        }
        return result;
    }
    onAfterSave(isSuccess, result) {
        if (isSuccess) {
            if (result.parameters && result.parameters.models)
                this.context.models.model = result.parameters.models.model;
        }
    }

    mixin() {
        return {
            data() {
                return {
                    engineeId: "",
                    registerId: "",
                    minDate: new Date(2024, 1, 1),
                    maxDate: new Date(2080, 12, 1),
                    currentDate: new Date(),
                    showPicker: false,
                    timeKey: "",
                    controlData: {
                        workflow: {},
                    },
                    models: {
                        model: {},
                    },
                    pageAction: "",
                    selectUser: {
                        selectComment: null,
                        leastReplyDate: null,
                        comment: null,
                        comments: [],
                        tran: [],
                        activity: "",
                        users: [],
                    },
                    showPinion: false,
                    radioArr: [
                        {
                            code: true,
                            name: "是",
                        },
                        {
                            code: false,
                            name: "否",
                        },
                    ],
                    auditType: "", // 审核类型 通过 退回
                };
            },
            computed: {
                // 新建状态或草稿状态 监理单位填写
                canEdit() {
                    if (
                        (this.pageAction == "create" ||
                            this.models.model.status == "draft") &&
                        this.controlData.isSupOrg
                    ) {
                        return true;
                    }
                    return false;
                },
                // 待处理状态 施工单位填写整改结果
                canWrite() {
                    if (
                        this.pageAction == "edit" &&
                        this.models.model.status == "waiting" &&
                        this.controlData.isConOrg
                    ) {
                        return true;
                    }
                    return false;
                },
                // 待审核状态 监理单位 审核
                canCheck() {
                    if (
                        this.pageAction == "edit" &&
                        this.models.model.status == "finished" &&
                        this.controlData.isSupOrg
                    ) {
                        return true;
                    }
                    return false;
                },
                // 操作记录
                history() {
                    if (
                        this.controlData.workflow &&
                        this.controlData.workflow.history &&
                        this.controlData.workflow.history.length > 0
                    ) {
                        return this.controlData.workflow.history;
                    } else {
                        return [];
                    }
                },
            },
            methods: {
                setDefaultDate() {
                    this.models.model.patrolTime = this.$formatter.formatDate(
                        new Date(),
                        "yyyy-MM-dd"
                    );
                },
                validator(val) {
                    if (val === null) {
                        return false;
                    } else {
                        return true;
                    }
                },
                // 打开选择时间弹窗
                showTimePicker(key) {
                    if(this.models.model[key]){
                        this.currentDate = new Date(this.models.model[key])
                    }
                    this.timeKey = key;
                    this.showPicker = true;
                },
                // 确定时间
                onConfirm(time) {
                    this.models.model[this.timeKey] = this.$formatter.formatDate(
                        time,
                        "yyyy-MM-dd"
                    );
                    this.showPicker = false;
                },
                // 保存
                onSave() {
                    this.models.model.engineeId = this.engineeId;
                    this.models.model.registerId = this.registerId;
                    this.super.save(this.models, false, "", true, "保存成功");
                },
                //提交
                onCommit() {
                    if (this.$refs.patrolPic.getUploadedCount() == 0) {
                        return this.$toast("请上传现场照片！");
                    }
                    this.$refs.form
                        .validate()
                        .then((res) => {
                            this.models.model.engineeId = this.engineeId;
                            this.models.model.registerId = this.registerId;
                            this.send();
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                },
                // 跳转到填写整改结果
                onRectification() {
                    let url = "/business/qzjx/mobileEquipment/equip/patrol/handle";
                    this.$framework.util
                        .getPromise(`/workflow/getWorkflowArgs`, {
                            formId: this.models.model.patrolId,
                        })
                        .then((res) => {
                            if (!res.pageAction || !res.assigneeId) {
                                this.$f7.preloader.hide();
                                return;
                            }
                            const params = {
                                pageAction: res.pageAction,
                                caseId: this.models.model.patrolId,
                                assigneeId: res.assigneeId,
                                registerId: this.models.model.registerId,
                                action:
                                    res.pageAction == "edit" ? "processEdit" : "processView",
                                formId: this.models.model.patrolId, // 用于获取流程数据
                                engineeId: this.models.model.engineeId,
                            };

                            if (res.pageAction === "view") {
                                Object.assign(params, { historyTaskId: res.historyTaskId });
                            } else {
                                Object.assign(params, { taskId: res.taskId });
                            }
                            let paramStr = [];
                            for (let key in params) {
                                paramStr.push(`${key}=${params[key]}`);
                            }
                            paramStr = paramStr.join("&");
                            this.$f7.view.current.router.navigate(url + `?${paramStr}`);
                        })
                        .catch((err) => {
                            this.$f7.preloader.hide();
                        })
                        .finally(() => { });
                },
                // 审核
                fnCheck(type) {
                    this.auditType = type;
                    this.selectUser.comment = "";
                    this.showPinion = true;
                },
                // 提交
                saveDetects() {
                    if (this.auditType == "pass") {
                        // 通过
                        this.showPinion = false;
                        this.send();
                    } else {
                        // 退回
                        this.$f7.preloader.show();
                        this.super.fnBackJump(
                            this.selectUser.comment,
                            (result) => {
                                this.$f7.preloader.hide();
                                if (result.success) {
                                    this.showPinion = false;
                                    this.refreshData("退回成功");
                                } else {
                                    this.$f7.dialog.alert(result.message);
                                }
                            },
                            (e) => {
                                this.$f7.preloader.hide();
                            },
                            "usertask2",
                            {
                                model: {
                                    patrolId: this.models.model.patrolId,
                                    leastReplyDate: this.selectUser.leastReplyDate,
                                },
                            }
                        );
                    }
                },
                refreshData(msg) {
                    this.$f7.dialog.alert(msg, () => {
                        this.$f7.popup.close();
                        this.$f7.views.current.router.back({ force: true });
                    });
                },
                // 刷新taskId
                reloadTaskId() {
                    this.$framework.util
                        .getPromise(`/workflow/getWorkflowArgs`, {
                            formId: this.models.model.patrolId,
                        })
                        .then((res) => {
                            if (!res.pageAction || !res.assigneeId) {
                                return;
                            }
                            if (res.pageAction !== "view") {
                                this.controlData.workflow.taskId = res.taskId;
                                this.controlData.workflow.instanceId = res.instanceId;
                            }
                        })
                        .catch((err) => {
                            this.$f7.preloader.hide();
                        })
                        .finally(() => { });
                },
            },
        };
    }
}
</script>

<style lang="less" scoped>
@import url("../../../../../../assets/css/commonPage.less");

@{deep} .v-workflow-list {
    padding: 0 16px;
}

@{deep}.accordion .accordion-item>.item-link>.item-content {
    padding-left: 16px !important;
}

@{deep}.accordion.accordion-list {
    background-color: #fff;
    margin-bottom: 10px;
}

@{deep}.list input[type="text"] {
    height: 22px;
}

@{deep}.field-pic.van-cell {
    &::after {
        border-bottom: none;
    }
}
</style>
